package com.dmall.graph.floodfill;

/**
 * @author: xiao1.wang
 * @date: 2022/6/19 23:07
 */
public class Solution1020 {

    private boolean[][] visited;
    private int count = 0;
    private int R, C;

    private int[][] dirs = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}};

    public int numEnclaves(int[][] grid) {
        R = grid.length;
        C = grid[0].length;
        this.visited = new boolean[R][C];

        for (int x = 0; x < R; x++) {
            for (int y = 0; y < C; y++) {
                if (!visited[x][y] && grid[x][y] == 1) {
                    count += dfs(grid, x, y);
                }
            }
        }
        return count;
    }

    private int dfs(int[][] grid, int x, int y) {
        visited[x][y] = true;
        int res = inBound(x, y) ? 0 : 1;
        int count = 1;
        for (int d = 0; d < 4; d++) {
            int nextx = x + dirs[d][0];
            int nexty = y + dirs[d][1];
            if (inArea(nextx, nexty) && !visited[nextx][nexty] && grid[nextx][nexty] == 1) {
                int dfs = dfs(grid, nextx, nexty);
                res = res * dfs;
                count = count + dfs;
            }
        }
        return res == 0 ? 0 : count;
    }

    private boolean inBound(int x, int y) {
        return x == 0 || x == R - 1 || y == 0 || y == C - 1;
    }

    private boolean inArea(int x, int y) {
        return x >= 0 && x < R && y >= 0 && y < C;
    }

    public static void main(String[] args) {
        int[][] grid = {
                {0, 0, 0, 0},
                {1, 0, 1, 0},
                {0, 1, 1, 0},
                {0, 0, 0, 0}
        };
        Solution1020 solution1020 = new Solution1020();
        System.out.println(solution1020.numEnclaves(grid));
    }
}
